package com.yehui.spring.dependency;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

/**
 * @author 业徽
 * @date 2021/6/28
 */
@Component
public class DependencyInjectAndFindDemo {

    @Autowired
    private BeanFactory beanFactory;

    @Autowired
    private Environment environment;

    public static void main(String[] args) {
        final AnnotationConfigApplicationContext applicationContext =
                new AnnotationConfigApplicationContext();

        applicationContext.register(DependencyInjectAndFindDemo.class);

        applicationContext.refresh();

        applicationContext.getBean(DependencyInjectAndFindDemo.class).dependencyInjectAndFindInnerBean(applicationContext);

    }

    public void dependencyInjectAndFindInnerBean(ApplicationContext applicationContext) {
        BeanFactory findBeanFactory = null;
        Environment findEnvironment = null;
        try {
            findBeanFactory = applicationContext.getBean(BeanFactory.class);
            findEnvironment = applicationContext.getBean(Environment.class);
        } catch (BeansException e) {
            // ignore
        }

        // 这种内建的，依赖注入是可以的，依赖查找是不行的，也可用通过 Aware 接口获取
        System.out.printf("inject beanFactory: %s, find beanFactory: %s%n", beanFactory, findBeanFactory);
        System.out.printf("inject environment: %s, find environment: %s%n", environment, findEnvironment);
    }

}
